package com.yuncommunity.runcircle.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.PowerManager;
import android.support.annotation.Nullable;
import android.view.View;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.maps.AMap;
import com.yuncommunity.runcircle.MainActivity;
import com.yuncommunity.runcircle.conf.UserInfo;
import com.yuncommunity.runcircle.db.DBHelper;
import com.yuncommunity.runcircle.item.LocationItem;

/**
 * Created by oldfeel on 15-11-29.
 */
public class LocationService extends Service {
    public static final int STATE_NORMAL = 1; // 正常状态
    public static final int STATE_RUN_PREPARE = 2; // 准备跑步状态
    public static final int STATE_RUNNING = 3; // 跑步状态
    public static final int STATE_PUSH = 4; // 暂停状态

    private int state = STATE_NORMAL;
//    private int state = STATE_RUNNING;

    private final IBinder mBinder = new LocalBinder();
    private LocationManagerProxy mAMapLocationManager;
    private DBHelper dbHelper;
    private MainActivity activity;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    private PowerManager mPowerManager;// 电源管理服务
    private PowerManager.WakeLock mWakeLock;// 屏幕灯

    @Override
    public void onCreate() {
        super.onCreate();
        dbHelper = DBHelper.getInstance(this);
        mAMapLocationManager = LocationManagerProxy.getInstance(this);
        UserInfo userInfo = UserInfo.getInstance(getApplicationContext());
        time = userInfo.getTime();
        state = userInfo.getState();
        if (state != STATE_NORMAL) {
            mAMapLocationManager.requestLocationData(
                    LocationManagerProxy.GPS_PROVIDER, 5 * 1000, 5,
                    locationListener);
        }
        initSensor();

        // 电源管理服务
        mPowerManager = (PowerManager) this
                .getSystemService(Context.POWER_SERVICE);
        mWakeLock = mPowerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK
                | PowerManager.ACQUIRE_CAUSES_WAKEUP, "S");
        mWakeLock.acquire();
    }

    private void initSensor() {
        // 版本 4.4 以上的提供计步服务.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
            Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
            sensorManager.registerListener(sensorEventListener, sensor, SensorManager.SENSOR_DELAY_FASTEST);
        }
    }

    private float stepsAll;

    SensorEventListener sensorEventListener = new SensorEventListener() {
        @Override
        public void onSensorChanged(SensorEvent event) {
            if (event.sensor.getType() == Sensor.TYPE_STEP_COUNTER) {
                stepsAll = event.values[0];
            }
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
        }
    };

    public void setState(int state) {
        this.state = state;
    }

    public int getState() {
        return state;
    }

    public long getTime() {
        return time;
    }

    public class LocalBinder extends Binder {
        public LocationService getService() {
            return LocationService.this;
        }
    }

    /**
     * 准备跑步
     *
     * @param aMap
     */
    public void prepareRun(final MainActivity activity, AMap aMap) {
        this.activity = activity;
        state = STATE_RUN_PREPARE;
        activity.findGps.setVisibility(View.VISIBLE);
        activity.findGpsInfo1.setVisibility(View.VISIBLE);
        activity.findGpsInfo2.setVisibility(View.GONE);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                activity.findGpsInfo1.setVisibility(View.GONE);
                activity.findGpsInfo2.setVisibility(View.VISIBLE);
            }
        }, 5 * 1000);
        mAMapLocationManager.requestLocationData(
                LocationManagerProxy.GPS_PROVIDER, 5 * 1000, 5,
                locationListener);
        aMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_FOLLOW);
    }

    /**
     * 完成跑步
     *
     * @param aMap
     */
    public void completeRun(AMap aMap) {
        state = STATE_NORMAL;
        mAMapLocationManager.removeUpdates(locationListener);
        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
        if (onStateListener != null) {
            onStateListener.onEnd();
        }
    }

    Handler handler = new Handler();

    private LocationItem startItem;

    private int time;
    private AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation.getProvider().equals("gps") && state == STATE_RUN_PREPARE) {//gps定位,准备跑步
                state = STATE_RUNNING;
                if (activity != null && activity.findGps != null) {
                    activity.findGps.setVisibility(View.GONE);
                }
                startItem = dbHelper.startRun(aMapLocation, stepsAll);
                if (onStateListener != null) {
                    time = 0;
                    new Thread() {
                        @Override
                        public void run() {
                            while (state != STATE_NORMAL) {
                                try {
                                    Thread.sleep(1000);
                                    if (state == STATE_RUNNING) {
                                        time++;
                                        if (onStateListener != null) {
                                            onStateListener.updateTime(time);
                                        }
                                    }
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }.start();
                    onStateListener.onStart();
                }
            } else if (state == STATE_RUNNING) {
                if (aMapLocation.getLatitude() != 0 && aMapLocation.getLongitude() != 0 && state == STATE_RUNNING) {
                    LocationItem item = dbHelper.saveLocation(aMapLocation);
                    if (onStateListener != null) {
                        onStateListener.update(item, time);
                    }
                }
            }
        }

        @Override
        public void onLocationChanged(Location location) {

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };

    public LocationItem getStartItem() {
        return startItem;
    }

    public float getStepsAll() {
        return stepsAll;
    }

    OnStateListener onStateListener;

    public interface OnStateListener {
        public void onEnd();

        public void onStart();

        public void update(LocationItem locationItem, int time);

        void updateTime(int time);
    }

    public void setOnStateListener(OnStateListener onEndListener) {
        this.onStateListener = onEndListener;
    }

    @Override
    public void onDestroy() {
        UserInfo userInfo = UserInfo.getInstance(getApplicationContext());
        if (state == STATE_RUNNING || state == STATE_PUSH) {
            userInfo.saveTimeAndState(time, state);
            Intent intent = new Intent("com.yuncommunity.runcirle.service.RestartService");
            sendBroadcast(intent);
        } else {
            userInfo.clearTimeAndState();
        }

        if (mWakeLock != null) {
            mWakeLock.release();
        }
        super.onDestroy();
    }
}
